package com.wlient.springboot_fileupload.controller;


import com.wlient.springboot_fileupload.entity.UserImage;
import com.wlient.springboot_fileupload.service.UserImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/")
public class FileController {
    //         定义文件存放的父文件夹路径
    private static String parentPath = "D:" + File.separator + "file";

    @Autowired
    private UserImageService userImageService;

    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    @GetMapping("/show")
    public String show() {
        return "show";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {

        String result = "上传失败";

//        判断上传文件是否为空，若为空则返回错误信息
        if (file.isEmpty()) {
            return "上传失败";
        } else {
//         获取文件原名
            String originalFilename = file.getOriginalFilename();

//         获取源文件前缀
            String fileNamePrefix = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            //获取源文件后缀
            String fileNameSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//         将源文件前缀之后加上时间戳避免重名
            //String newFileNamePrefix = fileNamePrefix+new Date().getTime();
            MessageDigest md5 = MessageDigest.getInstance("md5");//md5加密，极小概率发生冲突，不一定没有
            byte[] md5Str = md5.digest(fileNamePrefix.getBytes("utf-8"));
            String newFileNamePrefix = new BigInteger(1, md5Str).toString(16);
//         得到上传后新文件的文件名
            String newFileName = newFileNamePrefix + fileNameSuffix;
//         创建一个新的File对象用于存放上传的文件
            File fileNew = new File(parentPath + File.separator + newFileName);
            try {
                file.transferTo(fileNew);
                UserImage userImage = new UserImage();
                if (userImageService.save(userImage.setImagepath(newFileName).setUserid("1740707149"))) {
                    result = "上传成功!路径为:" + newFileName;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    //下载文件
    @RequestMapping(value = "/download/{fileName}", method = RequestMethod.GET)
    public void download(@PathVariable(value = "fileName", name = "fileName", required = true) String fileName, HttpServletResponse response) {
//        通过response输出流将文件传递到浏览器
//        1、获取文件路径
        //2.构建一个文件通过Paths工具类获取一个Path对象
        System.out.println(fileName);
        Path path = Paths.get(parentPath, fileName);
        //判断文件是否存在
        if (Files.exists(path)) {
            //存在则下载
            //通过response设定他的响应类型
            //4.获取文件的后缀名
            String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
//            5.设置contentType ,只有指定contentType才能下载
            response.setContentType("application/" + fileSuffix);
//            6.添加http头信息
//            因为fileName的编码格式是UTF-8 但是http头信息只识别 ISO8859-1 的编码格式
//            因此要对fileName重新编码
            try {
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//            7.使用  Path 和response输出流将文件输出到浏览器
            try {
                Files.copy(path, response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //多文件上传
    @RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
    @ResponseBody
    public Object handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("file");
        List<String> list = new ArrayList<>();
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    String fileNamePrefix = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
                    String fileNameSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                    MessageDigest md5 = MessageDigest.getInstance("md5");//md5加密，极小概率发生冲突，不一定没有
                    byte[] md5Str = md5.digest(fileNamePrefix.getBytes("utf-8"));
                    String newFileNamePrefix = new BigInteger(1, md5Str).toString(16);
                    //得到上传后新文件的文件名
                    String newFileName = newFileNamePrefix + fileNameSuffix;
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(parentPath + File.separator + newFileName)));
                    stream.write(bytes);
                    stream.close();
                    UserImage userImage = new UserImage();
                    if (userImageService.save(userImage.setImagepath(newFileName).setUserid("1740707149"))) {
                        list.add(newFileName);
                    }

                } catch (Exception e) {
                    stream = null;
                    return "You failed to upload " + i + " => "
                            + e.getMessage();
                }
            } else {
                return "You failed to upload " + i
                        + " because the file was empty.";
            }
        }
        return list;
    }
}
